#include "Fish.h"
#include "StaticData.h"

USING_NS_CC;

enum ActionType
{
	k_Action_Animate,
	k_Action_MoveTo
};

Fish* Fish::create( FishType fishType/*=k_Fish_Type_Red*/ )
{
	Fish* fish=new Fish;
	fish->init(fishType);
	fish->autorelease();
	return fish;
}

bool Fish::init( FishType fishType /*= k_Fish_Type_Red*/ )
{
	_type=fishType;
	CCString* animationName=CCString::createWithFormat(StaticData::getInstance()->stringFromKey("fish_animation"),_type);
	CCAnimation* fishAnimation=CCAnimationCache::sharedAnimationCache()->animationByName(animationName->getCString());
	CCAnimate* fishAnimate=CCAnimate::create(fishAnimation);
	fishAnimate->setTag(k_Action_Animate);
	_fishSprite=CCSprite::create();
	addChild(_fishSprite);
	_fishSprite->runAction(CCRepeatForever::create(fishAnimate));
	return true;
}

CCRect Fish::getCollisionArea()
{
	CCAssert(getParent(),"You Should Call This After Add it as a child!");
	CCPoint origin=getParent()->convertToWorldSpace(getPosition());
	CCSize size=_fishSprite->getContentSize();
	return CCRect(origin.x-size.width*0.5, origin.y-size.height*0.5, size.width, size.height);
}

void Fish::beCaught()
{
	stopActionByTag(k_Action_MoveTo);
	CCDelayTime* delayTime=CCDelayTime::create(1);
	CCCallFunc* callFunc=CCCallFunc::create(this,callfunc_selector(Fish::beCaughtCallBack));
	CCFiniteTimeAction* seq=CCSequence::create(delayTime,callFunc,0);

	CCBlink* blink=CCBlink::create(1,8);
	CCFiniteTimeAction* spawn=CCSpawn::create(seq,blink,0);
	runAction(spawn);
}

void Fish::beCaughtCallBack()
{
	getParent()->removeChild(this,false);
}

void Fish::moveTo(CCPoint destination)
{
	CCPoint start=getParent()->convertToWorldSpace(getPosition());
	float duration=ccpDistance(start,destination)/10;
	CCMoveTo* moveto=CCMoveTo::create(duration,destination);
	CCCallFunc* callFunc=CCCallFunc::create(this,callfunc_selector(Fish::moveEnd));

	CCFiniteTimeAction* seq=CCSequence::create(moveto,callFunc,0);
	seq->setTag(k_Action_MoveTo);
	runAction(seq);
}

void Fish::moveEnd()
{
	getParent()->removeChild(this,false);
}

void Fish::reset()
{
	setRotation(0);
	setVisible(true);
}
